package com.jcx.ldzj.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcx.ldzj.dto.UserInfoDTO;
import com.jcx.ldzj.emun.MyCode;
import com.jcx.ldzj.emun.SystemCode;
import com.jcx.ldzj.entity.UserInfo;
import com.jcx.ldzj.service.ILoginSystemInfoService;
import com.jcx.ldzj.service.IUserInfoService;
import com.jcx.ldzj.utile.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ð¡Ìì
 * @since 2021-01-20
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/user-info")
@Api(value = "用户信息主", tags = "用户信息主")
public class UserInfoController extends ApiController {
    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private RedisUtil redisclient;

    @Autowired
    private ILoginSystemInfoService iLoginSystemInfoService;
    /**
     * 列表
     *
     * @param pageNum
     * @param pageSize
     * @param userInfo
     * @return
     */
    @RequiresPermissions("basic:userinfo:page")
    @GetMapping("/list")
    @ApiOperation(value = "列表", notes = "传入UserInfo对象")
    public R<IPage<UserInfo>> list(Integer pageNum, Integer pageSize, UserInfo userInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(userInfo);
        queryWrapper.orderByDesc("update_time_");
        if(userInfo.getDepId()!=null){
            queryWrapper.like("dep_id_",userInfo.getDepId());
            userInfo.setDepId(null);
        }
        IPage<UserInfo> page = iUserInfoService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return R.ok(page);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @RequiresPermissions("basic:userinfo:view")
    @ApiOperation(value = "详情", notes = "传入id")
    public R<UserInfo> view(@PathVariable("id") String id) {
        UserInfo user = iUserInfoService.getUserById(id);

        return R.ok(user);
    }

    /**
     * 增加修改用户信息
     *
     * @param userInfo
     * @return
     */
    @PostMapping
    @RequiresPermissions("basic:userinfo:add")
    @ApiOperation(value = "新增用户信息", notes = "传入UserInfo")
    public R save(@Valid @RequestBody UserInfoDTO userInfo) {
        iUserInfoService.findUser(userInfo);
        return iUserInfoService.addUser(userInfo);
    }
    /**
     * 修改用户信息
     * @return
     */
    @PutMapping
    @RequiresPermissions("basic:userinfo:update")
    @ApiOperation(value = "修改", notes = "传入userInfo")
    public R edit(@Valid @RequestBody UserInfoDTO userInfo) {
        iUserInfoService.findUser(userInfo);
        return iUserInfoService.updateUser(userInfo);
    }
    /**
     * 修改重置密码密码
     * @param userName           用户名称
     * @return @RequiresPermissions("basic:userinfo:updatePassword")
     */
    @PostMapping("/resetPassword")
    @RequiresPermissions("basic:userinfo:resetPassword")
    @ApiOperation(value = "重置密码", notes = "传入UserInfo")
    public R resetPassword(@ApiParam(value = "用户id", required = true) @RequestParam String userName) {
        return iUserInfoService.resetPassword(userName);
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    @RequiresPermissions("basic:userinfo:delete")
    @ApiOperation(value = "删除", notes = "传入id")
    public R del(@ApiParam(value = "主键集合", required = true) @PathVariable("ids") String id) {
        return this.success(iUserInfoService.deleteUser(id));
    }

    /**
     登录验证接口，根据用户名和密码进行验证
     *
     * @param userName 用户名
     * @param passWord 密码
     * @return
     */
    @GetMapping("/login")
    @ApiOperation(value = "登录", notes = "传入id")
    public R login(String userName, String passWord, String verificationCode, HttpSession session, HttpServletRequest request) {
        HttpSession session1 = request.getSession();
        Object result=session1.getAttribute("verification");
        log.info("传入验证码为：{}，查询验证码：{}",verificationCode,result);
        R r = iUserInfoService.verificationCode(verificationCode, result);
        if(!r.ok()){
            return r;
        }
        R<String> userInfoR = iUserInfoService.apassLogin(userName, passWord);
        if(userInfoR.getCode()!=0){
            return userInfoR;
        }
        userInfoR.setData(userName);
        try{
            long timeout = SecurityUtils.getSubject().getSession().getTimeout();

            System.out.println(timeout+"毫秒");
            //加入用户登录信息/**/
            iLoginSystemInfoService.setOsAndBrowserInfo(userInfoR);
        }catch (Exception e){
            log.error("存储用户登录信息出错，错误原因{}",e);
        }
        if(iUserInfoService.isAdmin(userName)){
            ArrayList<String> strings = new ArrayList<>();
            strings.add("*:*:*");
            return R.ok(strings);
        }
        return R.ok(redisclient.lRange(SystemCode.USER_PERMISSIONS + userName, 0, -1));
    }
    /**
     * 修改重置密码密码
     * @param newPassword  新密码
     * @return @RequiresPermissions("basic:userinfo:updatePassword")
     */
    @PostMapping("/updatePwdOld")
    @ApiOperation(value = "自身修改密码", notes = "传入UserInfo")
    public R updatePwdOld(
                            @ApiParam(value = "老密码", required = true) @RequestParam String oldPassword,
                            @ApiParam(value = "新密码", required = true) @RequestParam String newPassword) {
        return iUserInfoService.updatePwdOld(oldPassword, newPassword);
    }

    /**
     * 修改重置密码密码
     *
     * @param userName           用户名称
     * @param emailCode 验证码
     * @param newPassword  新密码
     * @return @RequiresPermissions("basic:userinfo:updatePassword")
     */
    @PutMapping("/updatePassword")
    @ApiOperation(value = "自身修改密码", notes = "传入UserInfo")
    public R updatePassword(HttpSession session,
                            @ApiParam(value = "用户id", required = true) @RequestParam String userName,
                            @ApiParam(value = "验证码", required = true) @RequestParam String emailCode,
                            @ApiParam(value = "新密码", required = true) @RequestParam String newPassword) {
        return iUserInfoService.updatePassword(session,userName, emailCode, newPassword);
    }
    /**
     * 获取当前登录用户的信息
     * @return
     */
    @GetMapping("/getUser")
    @ApiOperation(value = "获取当前登录用户的信息")
    public R<UserInfo> getUser() {
        return iUserInfoService.getUser();
    }


    /**
     * 获取当前登录用户的信息
     * @return
     */
    @GetMapping("/sessionStop")
    @ApiOperation(value = "停止当前的session")
    public R sessionStop() {
        SecurityUtils.getSubject().logout();
        return R.ok("成功");
    }

    /**
     * 用户修改自身基本资料
     * @return
     */
    @PutMapping("/updateThis")
    @ApiOperation(value = "修改", notes = "传入userInfo")
    public R updateThis(@Valid @RequestBody UserInfo userInfo) {
        if(!iUserInfoService.updateById(userInfo)){
            return R.failed(MyCode.变更用户信息失败_请重试);
        }
        redisclient.hPut(SystemCode.USER_MAP,userInfo.getUserName(), JSONObject.toJSONString(userInfo));
        return R.ok("成功");
    }
}
